from res import *
import requests

clear_screen()
title()

def return_api(api,song_name):
    api = str(f'{api}{song_name}&num=10&type=json&br=1')
    return api

def show_song_list(api):
    try:
        response  = requests.get(api)
        response.raise_for_status()
        data = response.json()
        main_data = data['data']
        for item in main_data:
            print_b(f"[{item['n']}]{item['title']} 歌手: {item['singer']} id: {item['songid']}")

    except requests.RequestException as e:
        print_r(f"请求失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except KeyError as e:
        print_r(f"解析数据失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    
def user_choose():
    try:
        choice = int(input_g("请输入要下载的歌曲序号: "))
        if 1 <= choice <= 10:
            clear_screen()
            title()
            return choice
        else:
            print_r("无效的序号")
            input_g('按回车键返回---->')
            clear_screen()
            os.system(f"{p()} wangyiyun.py")
            exit()
    except ValueError:
        print_r("请输入有效的数字序号")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} wangyiyun.py")
        exit()

def download_music(url,save_path,name):
    try:
        name = name.replace("/", "_")
    except AttributeError:
        name = name
    save_path = f'{save_path}[网易云]{name}.mp3'
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status() 
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192): 
                file.write(chunk)
        print_g(f"文件已成功下载到 {save_path}")
        print_g(f'感谢使用!')
        input_g('按回车键返回---->')
        clear_screen()  
        os.system(f"{p()} wangyiyun.py")
        exit()
    except requests.exceptions.RequestException as e:
        print_r(f"下载失败：{e}")
        print_g('感谢使用!')
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py") 
        exit()
    except FileNotFoundError as e:
        name = name.replace("/", "_")
        save_path = f'{save_path}[网易云]{name}.mp3'
        try:
            response = requests.get(url, stream=True)
            response.raise_for_status() 
            with open(save_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192): 
                    file.write(chunk)
            print_g(f"文件已成功下载到 {save_path}")
            print_g(f'感谢使用!')
            input_g('按回车键返回---->')
            clear_screen()  
            os.system(f"{p()} wangyiyun.py")
            exit()
        except requests.exceptions.RequestException as e:
            print_r(f"下载失败：{e}")
            print_g('感谢使用!')
            input_g('按回车键返回---->')
            clear_screen()
            os.system(f"{p()} main.py") 
            exit()

def get_music_info(api,choose,save_path):
    json_api = str(f'{api}{song_name}&n={choose}&type=json&br=2')
    try:
        response  = requests.get(json_api)
        response.raise_for_status()
        data = response.json()
        print_db(f"歌曲名称:{data['title']}\n歌手: {data['singer']}\n封面:{data['cover']}\n网易云链接:{data['link']}\n下载链接:{data['music_url']}")
        second_confirmation = input_g('确认下载吗(y/n):')
        if second_confirmation == 'y':
            download_music(data['music_url'],save_path,data['title'])
        elif second_confirmation == 'n':
            os.system(f"{p()} wangyiyun.py")
        else:
            os.system(f"{p()} wangyiyun.py")


    except requests.RequestException as e:
        print_r(f"请求失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except KeyError as e:
        print(f"解析数据失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    print(json_api)


song_name = input_g("请输入网易云音乐歌曲名称(区分大小写): ")
save_path = input_g('请输入下载路径,默认本文件夹下的music文件夹:')
if save_path != '':
    if os.path.exists(save_path):
        next
    else:
        print_r("路径不存在,已使用默认下载路径")
        save_path = ''
else:
    next
if save_path != '':
    if not save_path.endswith('/'):
        save_path += '/'
else:
    save_path = 'music/网易云音乐/'

original_api = 'https://www.hhlqilongzhu.cn/api/dg_wyymusic.php?gm='
api = return_api(api=original_api,song_name=song_name)
print(f'\033[1;36msong_list_url:\033[0m{api}')
show_song_list(api)
choose = user_choose()
get_music_info(original_api,choose,save_path)
